/**
 * Copyright (c) 2018, 西安星沙网络科技-版权所有
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.waleychain.exchange.service.impl.trade;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.waleychain.exchange.core.SysParaKey;
import cn.waleychain.exchange.core.logger.LoggerHelper;
import cn.waleychain.exchange.core.utils.StringUtils;
import cn.waleychain.exchange.feign.MarketServiceFeign;
import cn.waleychain.exchange.model.Market;
import cn.waleychain.exchange.service.sys.ConfigService;
import cn.waleychain.exchange.service.trade.CacheDataService;
import cn.waleychain.exchange.service.trade.KLineService;

@Service
public class KLineServiceImpl implements KLineService {

	private static final Logger mLog = LoggerFactory.getLogger(KLineServiceImpl.class);
	
	@Autowired
	private CacheDataService cacheDataService;
	
	@Autowired
	private MarketServiceFeign marketFeign;
	
	@Autowired
	private ConfigService configFeign;
	
	@Override
	public Map<String, Object> fetchKLineData(long marketId, String dataType, int kLimit) throws Exception {

		//lines K线图, 依次是: 时间(ms), 开盘价, 最高价, 最低价, 收盘价, 成交量
		List<String> rs = this.getData(marketId, dataType, kLimit);
		Market market = marketFeign.fetchMarketByCache(marketId);
		Map<String, Object> maps = new HashMap<>();
		Map<String, Object> map = new HashMap<>();
		
		if (market != null) {
			map.put("contractUnit", market.getName());
		} else {
			return maps;
		}
		
		//获取换算比率
		String usdcny = configFeign.fetchSystemConfigValue(SysParaKey.TRADE_CONFIG_CASH_US);
		map.put("USDCNY",usdcny);
		
		List<Object> lineList = new ArrayList<>();
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:ss:mm");
		if (rs != null && rs.size() > 0) {
			try {
				for (Iterator<String> it = rs.iterator(); it.hasNext();) {
					String var1 = (String) it.next();
					String[] s1 = var1.split(",");
					List<String> stringList = Arrays.asList(s1);
					List<Object> returnList = new ArrayList<>();
					long time = sd.parse(String.valueOf(stringList.get(0))).getTime();
					returnList.add(0,time);
					returnList.add(1, new BigDecimal(stringList.get(1))); //开盘
					returnList.add(2, new BigDecimal(stringList.get(3))); //闭盘
					returnList.add(3, new BigDecimal(stringList.get(4))); //最高
					returnList.add(4, new BigDecimal(stringList.get(2))); //最低
					returnList.add(5, new BigDecimal(stringList.get(5)));
					lineList.add(returnList);
					
					rs.removeAll(stringList);
				}
			} catch (ParseException e1) {
				LoggerHelper.printLogErrorNotThrows(mLog, e1, "组装K线数据异常");
			}
		}
		
		List<Object> list = new ArrayList<>();
		for (int i = lineList.size() - 1; i >= 0; i--) {
			list.add(lineList.get(i));
		}
		
		map.put("data", list);
		map.put("symbol", market.getTitle());
		map.put("marketName", market.getName());
		map.put("topTickers", new ArrayList<>());
		map.put("url", "");
		maps.put("isSuc", true);
		maps.put("datas", map);
		
		return maps;
	}

	public List<String> getData(long marketId, String dataType, int limit) throws Exception {
		
		if (StringUtils.isBlank(dataType)) {
			return null;
		} else {
			Map<String, List<String>> map = this.cacheDataService.getKLines2Cache(marketId);
			if (map != null) {
				List<String> rs = map.get(dataType);
				if (rs != null && rs.size() > 0) {
					return rs.subList(1, Math.min(rs.size(), 1 + limit));
				}
			}
			
			return null;
		}
	}
}
